import org.grailsext.annotation.Privileged
import java.lang.reflect.Field
import java.util.Collections
import org.apache.commons.collections.CollectionUtils

// Base class for all Controllers
abstract class BaseController {

	static departmentMap = ['招商部':'招商部'
		,'营运部':'营运部'
		,'市场部':'市场部'
		,'信息部':'信息部'
		,'行政部':'行政部'
		,'人事部':'人事部'
		,'财务部':'财务部'
		,'采购部':'采购部'
		,'商品部':'商品部'
		,'结算中心':'结算中心'
		,"发展部":"发展部"
		,"物业部":"物业部"]
//		,"物业工程部":"物业工程部"
//		,"物业保安部":"物业保安部"
//		,"物业保洁部":"物业保洁部"]

	// Authentication interception method for all access
	def auth(){
		println "Start to check user login: ${session.userId}"
		if(!session.userId){
			println "User not login"
			def originalRequestParams = [controller:controllerName, action:actionName]
			originalRequestParams.putAll(params)
			session.originalRequestParams = originalRequestParams
			flash.message = "You must login first"
			redirect(controller:'user', action:'login')
			return false
		}
		println "Action Name: " + actionName

		// 'admin' user is the one
		if(session.userName != null && session.userName == 'admin'){
			println "You have super power!"
			return true;
		}

		// Loop to check all Action closures
		for (Field field : this.getClass().getDeclaredFields()) {
			// Find matched Action
			if (field.getName().equals(actionName)) {
				Privileged annoPriv = (Privileged)field.getAnnotation(Privileged.class);
				if(annoPriv == null){
					println "No annotation for action " + field.getName()
					continue;
				}

				// loop to find all privileges assigned to user
				def user = User.get(session.userId)
				def privileges = new HashSet()//Privilege should be unique
				for(Role r : user.roles){
					println "user has role: ${r.roleName}"
					CollectionUtils.addAll(privileges, r.privileges.iterator());
//					privileges.add(r.privileges)
				}
				println "user has privileges ${privileges}}"

				String[] requiredPrivileges = annoPriv.privileges();
				// loop to check whether privileged
				boolean isPrivileged = false;
				for (String s : requiredPrivileges) {
					for(Privilege p : privileges){
						println "${p.privName} == ${s.trim()}"
						if(p.privName == s.trim()){
							isPrivileged = true;
						}
					}
				}
				if(isPrivileged == false){
					println "Access denied, privilege ${requiredPrivileges} required"
					flash.message = "You are not allowed to access this page."
					redirect(action:'accessDenied')
					return false
				}
				break;// break for found the closure
			}
		}
		println "Authentication completed!"
	}

	def accessDenied = {
		println "Redirect to user login page"
		render(view:'user/login')
	}

	def boolean saveEntity(entity){
		if(entity.hasErrors()){
			println "Entity ${entity} has errors"
			entity.errors.each{
				println it
			}
			flash.message = entity.errors
			return false
		} else {
			if(!entity.save(flush:true)){
				println "Save entity ${entity} with errors"
				entity.errors.each{
					println it
					flash.message = entity.errors
				}
				return false
			}
			return true
		}
	}
}
